<script>
	/**
	 * vuex管理登录状态，具体可以参考官方登录模板示例
	 */
	import {
		mapMutations
	} from "vuex";
	import APPUpdate from "@/plugins/APPUpdate";
	import {
		getClipboardData
	} from "@/js_sdk/h5-copy/h5-copy.js";
	import config from "@/config/config";
	import {
		whetherNavigate
	} from "@/utils/Foundation"; //登录跳转
	import {
		getUserInfo
	} from "@/api/members";

	// 悬浮球
	import {
		mpAutoLogin
	} from "@/api/connect.js";
	import storage from "@/utils/storage.js";
	let platform
	// #ifdef MP-WEIXIN
	platform = 1
	// #endif
	// #ifdef MP-TOUTIAO
	platform = 2
	// #endif
	// #ifdef MP-KUAISHOU
	platform = 3
	// #endif
	// #ifdef H5
	platform = 4
	// #endif
	export default {
		data() {
			return {
				config,
			};
		},

		/**
		 * 监听返回
		 */
		onBackPress(e) {
			if (e.from == "backbutton") {
				let routes = getCurrentPages();
				let curRoute = routes[routes.length - 1].options;
				routes.forEach((item) => {
					if (
						item.route == "pages/tabbar/cart/cartList" ||
						item.route.indexOf("pages/product/goods") != -1
					) {
						uni.redirectTo({
							url: item.route,
						});
					}
				});

				if (curRoute.addId) {
					uni.reLaunch({
						url: "/pages/tabbar/cart/cartList",
					});
				} else {
					uni.navigateBack();
				}
				return true; //阻止默认返回行为
			}
		},
		methods: {
			...mapMutations(["login"]),
		},
		onLaunch: function() {
			uni.$set = this.$set
			uni.loadFontFace({
				family: 'HarmonyOS Sans SC',
				source: 'url("https://www.ljlctrip.com/HarmonyOS_Sans_SC_Medium.ttf")',
				success() {
					console.log('success')
				}
			})
			// #ifdef APP-PLUS
			this.checkArguments(); // 检测启动参数
			APPUpdate();

			// 重点是以下： 一定要监听后台恢复 ！一定要
			plus.globalEvent.addEventListener("newintent", (e) => {
				this.checkArguments(); // 检测启动参数
			});
			// #endif

			// #ifdef MP-WEIXIN
			this.applyUpdateWeChat();
			// #endif
			let version = "1.3.0"
			console.log(
				`\n %c 云AI助手V${version} %c 公众号：南羽工作室 \n\n`,
				"color: #ffffff; background: #3c9cff; padding:5px 0;",
				"color: #3c9cff;background: #ffffff; padding:5px 0;"
			);
			let oldVersion = uni.getStorageSync('version') || ''
			// 处理上个版本和这个版本缓存不一致的内容
			if (version != oldVersion) {
				uni.removeStorageSync('chat')
				uni.setStorageSync('version', version)
			}
			// 获取基本配置
			this.getLoginConfig();
			this.getRobot();
			this.getModelList();
			this.getAd();
		},

		onShow() {
			// #ifndef H5
			// this.getClipboard();
			// #endif
		},
		methods: {
				// 获取登录配置
				async getLoginConfig() {
					const {
						data
					} = await this.$u.get("/app/application/info/loginConfig");
					this.$store.commit('setLoginConfig', data)
				},
				// 获取AI配置
				async getRobot() {
					const {
						data
					} = await this.$u.get("app/robot/info/info", {
						params: {
							id: 1,
						},
					});
					this.$store.commit('setRobot', data)
				},
				// 获取广告
				async getAd() {
					const {
						data
					} = await this.$u.post("/app/ad/info/list");
					data.forEach(item => {
						// 处理富文本转义的问题
						item.desc = item.desc?.replace(
							/\<p\>&lt;ad(.*?)&gt;&lt;\/ad&gt;\<\/p\>/g,
							'<ad$1></ad>'
						);
					})
					uni.setStorageSync("ad", data?.filter(item => item.platform === platform || item
						.platform === 0) || []);
				},
				// 获取模型
				async getModelList() {
					const {
						data
					} = await this.$u.post('/app/chatgpt/model/list')
					this.$store.commit('setModelList', data)
					console.log("*****getModelList********")
					if (!this.$store.state.model.id) {
						this.$store.commit('setModel', data?.[0] || {})
					}
				},
			
			applogin(shareUserId) {
				shareUserId=uni.getStorageSync("shareUserId")
				console.log("applogin······························")
				uni.login({
					success: (res) => {
						let code = res.code;
						mpAutoLogin({
							code,shareUserId
						}).then((res) => {
							storage.setAccessToken(res.data.result.accessToken);
							storage.setRefreshToken(res.data.result.refreshToken);
								uni.setStorageSync("isccccc",res.data.result.isshenghe)
							// 登录成功
							uni.showToast({
								title: "登录成功!",
								icon: "none",
							});
							//获取用户信息
							getUserInfo().then((user) => {
								storage.setUserInfo(user.data.result);
								storage.setHasLogin(true);
								uni.$emit("loginSuccess")
							});
						});
					},
				});
			},
			/**
			 * 微信小程序版本提交更新版本 解决缓存问题
			 */
			applyUpdateWeChat() {
				const updateManager = uni.getUpdateManager();

				updateManager.onCheckForUpdate(function(res) {
					// 请求完新版本信息的回调
				});

				updateManager.onUpdateReady(function(res) {
					uni.showModal({
						title: "更新提示",
						content: "发现新版本，是否重启应用？",
						success(res) {
							if (res.confirm) {
								// 新的版本已经下载好，调用 applyUpdate 应用新版本并重启
								updateManager.applyUpdate();
							}
						},
					});
				});
				updateManager.onUpdateFailed(function(res) {
					// 新的版本下载失败
				});
			},

			//  TODO 开屏广告 后续优化添加
			launch() {
				try {
					// 获取本地存储中launchFlag标识 开屏广告
					const value = uni.getStorageSync("launchFlag");
					if (!value) {
						// this.$u.route("/pages/index/agreement");
					} else {
						//app启动时打开启动广告页
						var w = plus.webview.open(
							"/hybrid/html/advertise/advertise.html",
							"本地地址", {
								top: 0,
								bottom: 0,
								zindex: 999,
							},
							"fade-in",
							500
						);
						//设置定时器，4s后关闭启动广告页
						setTimeout(function() {
							plus.webview.close(w);
							APPUpdate();
						}, 3000);
					}
				} catch (e) {
					// error
					uni.setStorage({
						key: "launchFlag",
						data: true,
						success: function() {
							console.log("error时存储launchFlag");
						},
					});
				}
			},

			/**
			 * 获取粘贴板数据
			 */
			async getClipboard() {
				let res = await getClipboardData();
				/**
				 * 解析粘贴板数据
				 */
				if (res.indexOf(config.shareLink) != -1) {
					uni.showModal({
						title: "提示",
						content: "检测到一个分享链接是否跳转？",
						confirmText: "跳转",
						success: function(callback) {
							if (callback.confirm) {
								const path = res.split(config.shareLink)[1];
								if (path.indexOf("tabbar") != -1) {
									uni.switchTab({
										url: path,
									});
								} else {
									uni.navigateTo({
										url: path,
									});
								}
							}
						},
					});
				}
			},

			/**
			 * h5中打开app获取跳转app的链接并跳转
			 */
			checkArguments() {
				// #ifdef APP-PLUS
				setTimeout(() => {
					const args = plus.runtime.arguments;
					if (args) {
						const argsStr = decodeURIComponent(args);
						const path = argsStr.split("//")[1];
						if (path.indexOf("tabbar") != -1) {
							uni.switchTab({
								url: `/${path}`,
							});
						} else {
							uni.navigateTo({
								url: `/${path}`,
							});
						}
					}
				});
				// #endif
			},
		},
	};
</script>
<style>
	@import "@/static/css/main.css";
	/* @import "@/static/css/icon.css"; */
	@import "@/static/css/animation.css";
	
	
	.uni-progress-bar{
		border-radius: 20px;
	}
	.uni-progress-inner-bar{
		border-radius: 20px;
	}
	.combg {
		width: calc(100% - 60rpx);
		padding: 32rpx;
		margin: 30rpx auto;
		background: #fff;
		box-shadow: 0 40rpx 0 -22rpx rgb(221 138 0 / 23%), 0 -9rpx 0 0 rgb(105 100 87 / 14%) inset;
		border-radius: 50rpx;
	}
	.uicon{
		vertical-align: middle;
	}
	.listtitle {
		text-align: left;
		width: 686rpx;
		margin: 0 auto;
	}
	
	.listtitle .titlea {
		width: 44rpx;
		height: 44rpx;
		vertical-align: middle;
		margin-right: 5rpx;
	}
	
	.listtitle text {
		font-weight: bolder;
		vertical-align: middle;
		font-size: 34rpx;
		color:#594e3f;
	}
	
</style>
<style lang="scss">
	@import "uview-ui/index.scss";
	@import "style/theme.scss";

	/deep/ .u-title {
		color: #000 !important;
		font-size: 36rpx !important;
		font-family: HarmonyOS Sans SC;
		font-weight: bolder;
	}

	// -------适配底部安全区  苹果x系列刘海屏
	// #ifdef MP-WEIXIN
	.mp-iphonex-bottom {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);
		box-sizing: content-box;
		height: auto !important;
		padding-top: 10rpx;
	}

	// #endif

	body {
		background-color: $bg-color;
	}

	/************************ */
	.w200 {
		width: 200rpx !important;
	}

	.flex1 {
		flex: 1; //必须父级设置flex
	}
	
	
</style>
